/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "../Finder.h"
#include "../FileSystem.h"
#include <win32/win32.h>

namespace liba
{
namespace filesystem
{

template<class T, int(__stdcall* F)(T) >
class SysHandle
{
public:
	SysHandle( T t ):
		t(t)
	{}

	~SysHandle(){ F(t);};

	operator const T&()
	{
		return t;
	}
private:
	T t;
};

bool find(Finder * finder, const filesystem::String & base_path, const std::string & mask)
{
	static const const std::string THIS_FOLDER(".");
	static const const std::string PARENT_FOLDER("..");

	WIN32_FIND_DATA data;
	memset( &data, 0, sizeof( data ) );
	filesystem::String what = base_path.empty() ? mask.c_str() : base_path + "/" + mask.c_str();
	SysHandle<HANDLE,::FindClose> hFind  = ::FindFirstFile( what.c_str() ,&data );
	if( hFind == INVALID_HANDLE_VALUE )
		return false;
	do
	{
		if( data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
		{
			if( THIS_FOLDER != data.cFileName &&
                PARENT_FOLDER != data.cFileName )
			{
				if( base_path.empty() )
				{
					if( !finder->on_folder( data.cFileName ) )
						return true;
				}
				else
				{
					if( !finder->on_folder( base_path + "/" + data.cFileName ) )
						return true;
				}
			}
		}
		else
		{
			if( base_path.empty() )
			{
				if( !finder->on_file( data.cFileName ) )
					return true;
			}
			else
			{
				if( !finder->on_file( base_path + "/" + data.cFileName ) )
					return true;
			}
		}
	}while( ::FindNextFile( hFind, &data ) );

	return true;
}

} // namespace converter
} // namespace liba

